import { create } from 'zustand'
import { persist } from 'zustand/middleware'

interface Message {
	id: number
	content: string
	senderId: number
	chatId: number
	type: 'text' | 'image'
	status: 'sent' | 'delivered' | 'read'
	sender: {
		id: number
		username: string
		nickname: string
		avatar: string
	}
}

interface ChatMessageState {
	messages: Record<number, Message[]> // chatId -> messages
	addMessage: (chatId: number, message: Message) => void
	setMessages: (chatId: number, messages: Message[]) => void
	getChatMessages: (chatId: number) => Message[]
}

export const useChatMessageStore = create<ChatMessageState>()(
	persist(
		(set, get) => ({
			messages: {},
			addMessage: (chatId, message) =>
				set((state) => ({
					messages: {
						...state.messages,
						[chatId]: [...(state.messages[chatId] || []), message],
					},
				})),
			setMessages: (chatId, messages) =>
				set((state) => ({
					messages: {
						...state.messages,
						[chatId]: messages,
					},
				})),
			getChatMessages: (chatId: number) => get().messages[chatId] || [],
		}),
		{
			name: 'chat-messages', // 持久化存储的名称
		}
	)
)
